package com.lzh.mybatisdemo.utils;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.springframework.core.annotation.AnnotationUtils;

import java.io.OutputStream;
import java.util.Objects;


/**
 * @Description:
 * @Author: ll
 * @Date: 2020/8/19 14:50
 */
public class JsonUtil {

     private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


     public static String stringify(Object object) {

          try {
               return OBJECT_MAPPER.writeValueAsString(object);
          } catch (Exception e) {
               e.printStackTrace();
          }

          return null;
     }

     public static String stringify(Object object, String... properties) {

          try {
               return OBJECT_MAPPER
                       .writer(new SimpleFilterProvider().addFilter(
                               Objects.requireNonNull(AnnotationUtils.getValue(
                                       AnnotationUtils.findAnnotation(object.getClass(), JsonFilter.class))).toString(),
                               SimpleBeanPropertyFilter.filterOutAllExcept(properties)))
                       .writeValueAsString(object);
          } catch (Exception e) {
               e.printStackTrace();
          }

          return null;
     }

     public static void stringify(OutputStream out, Object object) {

          try {
               OBJECT_MAPPER.writeValue(out, object);
          } catch (Exception e) {
               e.printStackTrace();
          }
     }

     public static void stringify(OutputStream out, Object object, String... properties) {

          try {
               OBJECT_MAPPER
                       .writer(new SimpleFilterProvider().addFilter(
                               Objects.requireNonNull(AnnotationUtils.getValue(
                                       AnnotationUtils.findAnnotation(object.getClass(), JsonFilter.class))).toString(),
                               SimpleBeanPropertyFilter.filterOutAllExcept(properties)))
                       .writeValue(out, object);
          } catch (Exception e) {
               e.printStackTrace();
          }
     }

     public static <T> T parse(String json, Class<T> clazz) {

          if (json == null || json.length() == 0) {
               return null;
          }

          try {
               return OBJECT_MAPPER.readValue(json, clazz);
          } catch (Exception e) {
               e.printStackTrace();
          }

          return null;
     }

}